<?php

namespace plugins\api\controller;

use app\exception\ModelException;
use app\model\SubContent;
use app\model\Tag;
use think\facade\Db;

class TagController extends BaseController
{
    public function index()
    {
        $param = $this->request->param();

        $limit = $param['limit'] ?? 10;
        $title = $param['title'] ?? '';
        $where = [
            ['seller_id', '=', $this->sellerId],
            ['website_id', '=', $this->siteId],
            ['lang', '=', $this->lang],
            ['is_del', '=', 1],
        ];
        if ($title) {
            $where[] = ['title', 'like', '%' . $title . '%'];
        }
        try {
            $tagModel = new Tag();
            $tagList = $tagModel->where($where)->paginate($limit)->each(function (&$item) {
                $contentNum = $item->subContent()->where('is_del', 1)->count();
                $item->article_count = $contentNum;
                $item->save();
            });
        } catch (\Exception $e) {
            throw new ModelException($e->getMessage());
        }
        return json(['code' => 0, 'total' => $tagList->total(), 'msg' => lang('成功'), 'data' => $tagList->all()]);
    }

    public function content()
    {
        $param = $this->request->param();

        $contentModel = new SubContent();
        $contentIds = Db::name('tag_sub_content')->where('tag_id', $param['tag_id'])->column('sub_content_id');

        $where = [
            ['seller_id', '=', $this->sellerId],
            ['is_del' , '=',1],
            ['id', 'in', $contentIds]
        ];

        $list = $contentModel->where($where)->with(['tag', 'cover' => function ($q) {
            $q->field('id,name,url,type');
        }, 'thumbnail' => function ($q) {
            $q->field('id,name,url,type');
        }, 'category'])->paginate($param['limit']);

        return json(['code' => 0, 'total' => $list->total(), 'msg' => lang('成功'), 'data' => $list->all()]);
    }

}